const express = require("express");
const router = express.Router();


//登录相关路由
router.get("/", (req, res) => {
    res.redirect("/login.html");
});
//html后缀，表示请求的页面
router.get("/login.html", (req, res) => {
    //获取cookie中的账号和密码信息
    // console.log(req.cookies);
    console.log(req.signedCookies);
    //响应页面模板，并传递数据
    res.render("login", {
        title: "登录",
        cookiesBean: {
            account: req.signedCookies.account,
            password: req.signedCookies.password
        }
    });
});
//html后缀，表示请求的页面
router.get("/logout.do", (req, res) => {
    //清空session
    delete req.session.loginBean;
    res.redirect("/login.html");
});
//do后缀，表示处理请求
router.post("/login.do", (req, res) => {
    //获取提交的数据
    const {password, account, rem} = req.body;
    //数据验证
    if (!account || account.trim().length < 5) {
        // res.redirect("/login.html?msg=账号长度必须大于5位");
        res.render("login", {
            title: "登录",
            msg: "账号长度必须大于5位"
        });
    }
    if (!password || password.length < 3) {
        // res.redirect("/login.html?msg=账号长度必须大于5位");
        res.render("login", {
            title: "登录",
            msg: "密码长度必须大于3位"
        });
    }
    if (account == "admin" && password == "123") {
        req.session.loginBean = {
            account, password
        }
        res.app.locals.username = account;
        if (rem == "1") {
            //req.cookies，获取所有cookie
            //在cookie中保存账号和密码
            //res，响应对象
            res.cookie("account", account, {maxAge: 1000 * 60 * 60 * 24 * 7, signed: true});//maxAge单是毫秒
            res.cookie("password", password, {maxAge: 1000 * 60 * 60 * 24 * 7, signed: true});
        } else {
            res.cookie("account", "");
            res.cookie("password", "");
        }
        //登录成功重定向到/book/list.html
        res.redirect("/book/list.html");
    } else {
        res.render("login", {
            title: "登录",
            msg: "账号或密码错误"
        });
    }
});

module.exports = router;